// =============================================================
// CProperty
// ---------------------------------------
// Author : Woo-Hyun Kim
// Email : woorung@icu.ac.kr or woorung@nhncorp.com
// Date : Jul. 10, 2006
// =============================================================
#include "CProperty.h"

CProperty::CProperty(char *conf)
{
	if(access(conf, F_OK)<0) {
		cerr << "### ERROR : there is no " << conf << endl;
		exit(-1);
	}

	pthread_mutex_init(&_mutex, NULL);

	delim = '=';
	eol = '\n';
	comment = "#";
	ignore = " \t\r\n";

	CLineTokenizer *line_tokenizer = new CLineTokenizer();
	line_tokenizer->input(conf);
	line_tokenizer->format(1);
	line_tokenizer->filter(delim, eol, 100);
	
	vector< vector<string> > token;
	while(line_tokenizer->getToken(token)>0) {
		for(int i=0;i<token.size();i++) {
			string key = token[i][0];

			if(trim_key(key)<0) continue;

			property[key] = "";
			for(int j=1;j<token[i].size();j++) {
				property[key] += token[i][j];
				if(j+1<token[i].size()) property[key] += delim;
			}

			trim(property[key]);
		}

		token.clear();
	}

	delete line_tokenizer;
}

CProperty::~CProperty()
{
	pthread_mutex_destroy(&_mutex);
}

int CProperty::trim_key(string &str)
{
	// if comment, skip
	string::size_type pos = str.find_first_of(comment);
	if(pos!=string::npos) return -1;

	return trim(str);
}

int CProperty::trim(string &str)
{
	string tmp;

	// if whitespace at the first, ignore
	string::size_type pos = str.find_first_not_of(ignore);
	if(pos!=string::npos) tmp = str.substr(pos);
	str = tmp;

	// if whitespace at the last, ignore
	pos = str.find_last_not_of(ignore);
	if(pos!=string::npos) tmp = str.substr(0, pos+1);
	str = tmp;

	if(str.size()<=0) return -1;
	else return 1;
}

pair<string,string> &CProperty::get(pair<string,string> &kv)
{
#ifdef DEBUG
	print();
#endif

	pthread_mutex_lock(&_mutex);

	kv.second = property[kv.first];

	pthread_mutex_unlock(&_mutex);

	return kv;
}

int CProperty::print()
{
	pthread_mutex_lock(&_mutex);

	map<string,string>::iterator kv = property.begin();
	while(kv!=property.end()) {
		cout << "[" << kv->first << "]" << delim << "[" << kv->second << "]" << endl;

		kv++;
	}

	pthread_mutex_unlock(&_mutex);
}
